package com.lmabbe.common.global.redis;

import com.lmabbe.common.global.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

/**
 * @author lmabbe
 */
@Slf4j
public class CustomizerRedisCacheManager extends RedisCacheManager {

    public CustomizerRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        //名称中存在#标记进行到期时间配置
        if (!name.isEmpty() && name.contains(RedisKeyConstant.division)) {
            String[] ttl = name.split(RedisKeyConstant.division);
            if (StringUtils.isNumeric(ttl[1])) {
                //配置缓存到期时间
                int cycle = Integer.parseInt(ttl[1]);
                return super.createRedisCache(ttl[0], cacheConfig.entryTtl(Duration.ofSeconds(cycle)));
            }
        }
        return super.createRedisCache(name, cacheConfig);
    }
}